<template>
<div>
    <myheader></myheader>
    <mt-navbar v-model="selected" :fixed="fixed" class="top-navbar">
        <mt-tab-item id="recommend">推荐</mt-tab-item>
        <mt-tab-item id="life">生活</mt-tab-item>
        <mt-tab-item id="entertainment">娱乐</mt-tab-item>
        <mt-tab-item id="education">教育</mt-tab-item>
        <mt-tab-item id="automobile">汽车</mt-tab-item>
    </mt-navbar>
    <div class="article-list" v-infinite-scroll="loadMore" infinite-scroll-disables="loading" infinite-scroll-distance="10">
        <info-item v-for="(p,i) of data" :key="i" 
        :id ="p.id"
        :subject="p.subject"
        :description="p.description"
        :image="p.image"></info-item> 
    </div>
    
</div>
</template>
<script>
import header from '../components/header.vue'
import infoItem from '../components/infoitem.vue'
export default {
    components:{"myheader":header,infoItem},
    data(){
         return{
             selected:"recommend",
             data:[],
             loading:false,
             page:1,
             pagecount:0,
             fixed:false,
             
         }
    },
    methods:{
         getData(type,page){
             this.axios.get('/articles?type='+type+'&page='+page).then(res=>{
                var articles = res.data.articles;
                this.pagecount = res.data.pagecount
                //console.log(articles)
                articles.forEach(item=>{
                    if(item.image != null){
                        item.image = require(`../assets/images/zhihu/` + item.image)
                    }
                    this.data.push(item);
                });
                //console.log(this.data)
             })
         },
         loadMore(){
              this.loading = true;
              this.page++;
              if(this.page<=this.pagecount){
                  this.getData(this.selected,this.page)
              };
              this.loading=false;

         },
         handleScroll(){
             var scrollTop = window.pageYOffset || document.body.scrollTop;
             var navbarEle = document.querySelector('.top-navbar');
             
             if(navbarEle !== null){
                 var offsetTop = navbarEle.offsetTop;
                 this.fixed = scrollTop > offsetTop;
             }

         }
    },
    mounted(){
        this.getData(this.selected,this.page);
        window.addEventListener('scroll',this.handleScroll);
    },
    watch:{
        selected(value){
            this.page = 1
            this.data=[];
            this.getData(value,this.page)
        },
        
    }
}
</script>
<style scoped>

.article-list {
  margin-bottom: 60px;
}
</style>
